package com.project.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.GradeBean;
import com.project.bean.RoleBean;
import com.project.mapper.IGradeMapper;
import com.project.mapper.IRoleMapper;
import com.project.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Transactional
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private IRoleMapper roleMapper;

    @Autowired
    private IGradeMapper gradeMapper;

    @Override
    public IPage<RoleBean> findByItem(Integer pageNO) {
        return roleMapper.selectPage(new Page<>(pageNO, 5), null);
    }

    @Override
    public List<RoleBean> findAll() {
        return roleMapper.findAll();
    }

    @Override
    public RoleBean findById(Integer roleId) {
        RoleBean role = roleMapper.selectById(roleId);
        Set<GradeBean> gradeBeanSet = new HashSet<>();
        gradeBeanSet.addAll(gradeMapper.findByRoleId(roleId));
        role.setGradeBeans(gradeBeanSet);
        return role;
    }

    @Override
    public void del(Integer roleId) {
        roleMapper.delRole(roleId);
    }

    @Override
    public void update(Integer roleId, Integer[] gradeIdArray) {
        roleMapper.delRoleGrade(roleId);
        gradeMapper.addAll(roleId, gradeIdArray);

    }

    @Override
    public void add(RoleBean role, Integer[] gradeIdArray) {
        roleMapper.insert(role);
        gradeMapper.addAll(role.getId(), gradeIdArray);
    }
}
